<template>
    <div id="instructionInfo-content">
        <el-row class="form-content">
            <el-form label-width="69px">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="产品代码(名称):">
                            <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="searchForm.fundCode" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="证券代码(名称):">
                            <el-select
                                v-model="searchForm.stockCode"
                                filterable
                                :filter-method="getstockCodeList"
                                @visible-change="handleStockVisibleChange"
                                @clear="getstockCodeList('')"
                                clearable
                                size="mini"
                            >
                                <el-option
                                    v-for="i in stockCodeSelectData"
                                    :key="i.stockCode"
                                    :label="i.stockCode + ' ' + i.stockNameSt"
                                    :value="i.stockCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="委托方向:">
                            <el-select v-model="searchForm.orderDirection" clearable size="mini">
                                <el-option v-for="i in orderDirectionData" :key="i.dictKey" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="证券类别:">
                            <el-select v-model="searchForm.stockType" filterable clearable size="mini">
                                <el-option v-for="item in stockType" :key="item.dictKey" :value="item.dictKey" :label="item.dictKeyName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="业务类型:">
                            <el-select v-model="searchForm.businessType" clearable size="mini">
                                <el-option value="A" label="开放式基金"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-button type="primary" size="mini" @click="query">查询</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="指令序号:">
                            <el-input size="mini" placeholder="" v-model="searchForm.instNo"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="指令状态:">
                            <el-select v-model="searchForm.instStatus" size="mini">
                                <el-option v-for="(value, key) in instructionStatus" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="下达人:">
                            <el-select v-model="searchForm.directUser" filterable clearable size="mini">
                                <el-option
                                    v-for="item in orderUsers"
                                    :key="item.dictKey + item.dictCode"
                                    :value="item.dictCode"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="下达日期:">
                            <el-date-picker
                                v-model="directDate"
                                type="date"
                                placeholder="请选择"
                                value-format="yyyyMMdd"
                                format="yyyy/MM/dd"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-button type="primary" size="mini" @click="handleButtonClick('layout')">布局设置</el-button>
                        <el-button size="mini" @click="handleButtonClick('hide')" v-show="SHOW_SECURITY">{{
                            hideVisible ? '展开' : '隐藏'
                        }}</el-button>
                    </el-col>
                </el-row>
                <el-row v-if="!hideVisible">
                    <el-col :span="5">
                        <el-form-item label="资产单元编号(名称):">
                            <el-select v-model="searchForm.assetCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in assetCodeSelectData"
                                    :key="i.assetCode"
                                    :label="i.assetCode + ' ' + i.assetName"
                                    :value="i.assetCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="组合编码(名称):">
                            <el-select v-model="searchForm.fundAcCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in fundAccountCodeSelectData"
                                    :key="i.fundAccountCode"
                                    :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                    :value="i.fundAccountCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="15"></el-col>
                </el-row>
            </el-form>
        </el-row>
        <el-row class="table-content">
            <div style="height: calc(100% - 60px)">
                <el-table
                    :key="tableKey"
                    :data="dataSource"
                    border
                    v-loading="tableLoading"
                    element-loading-text="加载中"
                    size="mini"
                    height="100%"
                    ref="table"
                    @row-click="handleRow"
                    style="cursor: pointer"
                    highlight-current-row
                    highlight-hover-row
                    stripe
                    auto-resize
                    resizable
                    :default-sort="{ prop: sortProp, order: sortOrder }"
                    @sort-change="changeTableSort"
                >
                    <template v-for="(item, index) in showFieldList">
                        <el-table-column
                            show-overflow-tooltip
                            :key="index + 'name'"
                            :label="item.content"
                            :prop="item.id"
                            :min-width="item.minWidth"
                            :fixed="item.fixed"
                            :sortable="item.id == 'operate' ? false : 'custom'"
                            :sort-orders="['ascending', 'descending']"
                        >
                            <template slot="header">
                                <span>{{ item.content }}</span>
                            </template>
                            <template slot-scope="scope">
                                <span v-if="item.id == 'operate'">
                                    <el-button type="text" @click.stop="handleUpdateInst(scope.row)" :disabled="handleDisabled(scope.row)"
                                        >修改</el-button
                                    >
                                    <el-button type="text" @click.stop="handleBtnDel(scope.row)" :disabled="handleDisabled(scope.row)"
                                        >撤单</el-button
                                    >
                                </span>
                                <span v-else-if="item.id == 'instStatus'">
                                    {{ instructionStatus[scope.row.instStatus] }}
                                </span>
                                <span v-else-if="item.id == 'orderPriceType'">
                                    {{ scope.row.orderPriceType ? investPriceSelectData[scope.row.orderPriceType] : '--' }}
                                </span>
                                <span v-else-if="item.id == 'stockType'">
                                    {{ scope.row[item.id] ? stockTypePojo[scope.row[item.id]] : '--' }}
                                </span>

                                <span v-else-if="item.id == 'directTime'" style="display:block; text-align:center">
                                    {{ formatterDate(scope.row) }}
                                </span>

                                <span v-else-if="item.id == 'directUserName'">
                                    {{ scope.row.directUserName.trim() ? scope.row.directUserName : '--' }}
                                </span>
                                <span v-else-if="item.id == 'bulkType'">
                                    {{ scope.row.bulkType && scope.row.bulkType !== '0' ? Invest.bulkType[scope.row.bulkType] : '--' }}
                                </span>
                                <span v-else-if="item.id == 'intoInvestType'">
                                    {{ scope.row['orderDirection'] === 'E' ? scope.row.investTypeName || '--' : '--' }}
                                </span>
                                <span v-else-if="['orderBalance', 'orderAmount'].includes(item.id)" style="float:right">
                                    {{ scope.row[item.id] ? numberFormat(scope.row[item.id], 2) : '0' }}
                                </span>

                                <span v-else-if="item.id == 'orderPrice'" style="float:right">
                                    {{ scope.row[item.id] ? numberFormat(scope.row[item.id], 4) : '0' }}
                                </span>

                                <span v-else-if="item.id === 'calculateValue' || item.id === 'thresholdValue'">{{
                                    scope.row[item.id] != undefined
                                        ? numberFormat(scope.row[item.id], scope.row.unit) + unitShow(scope.row.unit)
                                        : '--'
                                }}</span>
                                <span v-else>{{ scope.row[item.id] || '--' }}</span>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>
            <el-pagination
                background
                @current-change="handleCurrentChange"
                layout="total, prev, pager, next"
                :current-page="pages.currentPage"
                :page-size="pages.pageSize"
                :total="pages.total"
            >
            </el-pagination>
        </el-row>
        <el-row class="tab-content">
            <el-tabs v-model="activeKey" style="height: 100%">
                <el-tab-pane label="指令明细" name="detail" class="inst-detail">
                    <div class="detail-container">
                        <InstructionDetail :key="detailKey" :detailFields="detailFields" :instructionInfo="clickRecord" :noData="noData" />
                    </div>
                </el-tab-pane>
                <el-tab-pane label="指令证券" name="stock">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table :msg="instStockMsg" v-loading="tabsLoading"></risk-table>
                    </div>
                </el-tab-pane>

                <el-tab-pane label="指令结果" name="result">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table
                            :msg="instResultMsg"
                            v-loading="tabsLoading"
                            @handleBtn="handleBtnLook"
                            :key="instResultMsgNumKey + 'instResultMsgNumKey'"
                            v-if="activeKey === 'result'"
                        ></risk-table></div
                ></el-tab-pane>
            </el-tabs>
        </el-row>
        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="CW_INST_INFO"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { dateFormat, numberFormat, unitShow, timeFormat, UUID, sortBy, getConfigItem } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import moment from 'moment';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';

import ColumnUtil from '../utils/column-util';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import RiskTable from '@/common/components/risk-table.vue';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import InstructionDetail from '../components/instruction-detail.vue';
import InstructionInfoClass from '../class/instruction-info-class';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'CWOpenFundOrderInfo',
    components: {
        RiskTableLayout,
        RiskTable,
        StatusTag,
        RiskEntryInput,
        InstructionDetail,
    },
})
export default class CWOpenFundOrderInfo extends InstructionInfoClass {
    @Prop()
    renderCount: number;
    unitShow = unitShow;
    numberFormat = numberFormat;
    ColumnUtil = new ColumnUtil();
    Invest: any = new Invest();
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');

    // 查询表单
    searchForm: any = {
        assetTypes: [],
        businessType: 'A',
        // directDate: Number(moment().format('YYYYMMDD')),
        directUser: '',
        fundCode: '',
        instNo: '',
        instStatus: '1',
        marketTypes: [],
        orderDirection: '',
        stockCode: '',
        stockType: '',
        stockTypes: [],
        assetCode: '',
        fundAcCode: '',
        sort: 'D_DIRECT_DATE' + ' ' + 'DESC' + ',' + 'D_DIRECT_TIME' + ' ' + 'DESC',
    };

    // 撤单表单
    cancelOrder: any = {
        cancelOrderType: '2',
        tradeUser: getUser().userCode, // 当前用户
        tradeUserName: getUser().userName, // 当前用户
        orderType: '4',
        instructionType: '10',
        instNo: '',
        originOuterOrderCode: '',
        outerOrderCode: UUID() + '-' + new Date().getTime(),
        requestId: UUID() + '-' + new Date().getTime(),
    };

    directDate: string = '';
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    investPriceSelectData: any = {}; // 价格模式
    innerOrderDirectionData: any[] = [];
    orderDirectionData: any[] = []; // 委托方向数据

    listMsgNumKey: number = 0; // 指令数据Key
    dataSource: any[] = []; // 指令表数据

    pages: pages = {
        pageSize: 50,
        currentPage: 1,
        total: 0,
    };

    // 全部表格列
    tableColumns: any[] = [
        { content: '指令序号', id: 'instNo', minWidth: 120, fixed: 'left' },
        { content: '产品代码', id: 'fundCode', minWidth: 120, fixed: 'left' },
        { content: '产品名称', id: 'fundName', minWidth: 120 },
        // { content: '组合编码', id: 'groupCode', minWidth: 150 },
        // { content: '组合名称', id: 'groupName', minWidth: 150 },
        // 考虑已存布局问题
        { content: '组合编码', id: 'groupCode', minWidth: 150 },
        { content: '组合名称', id: 'groupName', minWidth: 150 },
        { content: '证券代码', id: 'stockCode', minWidth: 120 },
        { content: '证券名称', id: 'stockName', minWidth: 120 },
        { content: '证券类别', id: 'stockType', minWidth: 120 },
        { content: '业务类型', id: 'businessTypeName', minWidth: 120 },
        { content: '委托方向', id: 'orderDirectionName', minWidth: 120 },
        { content: '投资类型', id: 'investTypeName', minWidth: 120 },

        { content: '转入组合编码', id: 'destCombiId', minWidth: 150 },
        { content: '转入组合名称', id: 'destCombiName', minWidth: 150 },
        { content: '转入证券代码', id: 'destSecurityCode', minWidth: 120 },
        { content: '转入证券名称', id: 'destSecurityName', minWidth: 120 },
        { content: '转入投资类型', id: 'intoInvestType', minWidth: 120 },
        { content: '巨额赎回', id: 'bulkType', minWidth: 120 },

        { content: '币种', id: 'curName', minWidth: 120 },
        { content: '指令价格(元)', id: 'orderPrice', minWidth: 150 },
        { content: '指令数量(张)', id: 'orderAmount', minWidth: 140 },
        { content: '指令金额(元)', id: 'orderBalance', minWidth: 150 },
        { content: '交易市场', id: 'marketName', minWidth: 120 },
        { content: '下达人', id: 'directUserName', minWidth: 100 },
        { content: '下达时间', id: 'directTime', minWidth: 120 },
        { content: '指令状态', id: 'instStatus', minWidth: 120, fixed: 'right' },
        { content: '操作', id: 'operate', minWidth: 120, fixed: 'right' },
    ];

    // 已选择字段列表(不包括固定字段)
    selectedFieldList: any[] = [];

    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '指令序号', id: 'instNo', fixed: 'left', minWidth: 120 },
        { content: '产品代码', id: 'fundCode', fixed: 'left', minWidth: 120 },
        { content: '指令状态', id: 'instStatus', fixed: 'right', minWidth: 120 },
        { content: '操作', id: 'operate', fixed: 'right', minWidth: 120 },
    ];

    showFieldList: any[] = []; // 要显示的表格列
    layoutDialog: boolean = false;

    // 指令明细字段
    detailFields: any[] = [
        [
            { content: '指令序号', id: 'instNo' },
            {
                content: '指令状态',
                id: 'instStatus',
                needFormat: true,
                formatter: value => (value != undefined ? this.instructionStatus[value] : '--'),
            },
            { content: '下达人', id: 'directUserName' },
            {
                content: '下达时间',
                id: 'directTime',
                needFormat: true,
                formatter: (value, row) => dateFormat(row['directDate']) + ' ' + timeFormat(row['directTime']) || '--',
            },
            {
                content: '指令价格(元)',
                id: 'orderPrice',
                needFormat: true,
                formatter: value => (value != undefined ? numberFormat(value, 4) : '--'),
            },
            {
                content: '指令数量(份)',
                id: 'orderAmount',
                needFormat: true,
                formatter: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
            {
                content: '指令金额(元)',
                id: 'orderBalance',
                needFormat: true,
                formatter: value => (value != undefined ? numberFormat(value, 2) : '--'),
            },
        ],
        [
            { content: '产品代码', id: 'fundCode' },
            { content: '产品名称', id: 'fundName' },
            { content: '组合编码', id: 'groupCode' },
            { content: '组合名称', id: 'groupName' },
            { content: '证券代码', id: 'stockCode' },
            { content: '证券名称', id: 'stockName' },
            { content: '证券类别', id: 'stockTypeName' },
        ],
        [
            { content: '投资类型', id: 'investTypeName' },
            { content: '业务类型', id: 'businessTypeName' },
            { content: '委托方向', id: 'orderDirectionName' },
            { content: '转入组合编码', id: 'destCombiId' },
            { content: '转入组合名称', id: 'destCombiName' },
            { content: '转入证券代码', id: 'destSecurityCode' },
            { content: '转入证券名称', id: 'destSecurityName' },
        ],
        [
            {
                content: '转入投资类型',
                id: 'investTypeName',
                needFormat: true,
                formatter: (value, row) => (row['orderDirection'] === 'E' && value && value !== '0' ? row.investTypeName || '--' : '--'),
            },

            {
                content: '巨额赎回',
                id: 'bulkType',
                needFormat: true,
                formatter: (value, row) => (value && value !== '0' ? this.Invest.bulkType[value] : '--'),
            },
            { content: '币种', id: 'curName' },
            { content: '交易市场', id: 'marketName' },
        ],
    ];

    activeKey: string = 'detail'; //  指令当前tabKey
    tableKey: number = 0;

    // 指令结果表格相关
    instResultMsg = {
        returnData: {},
        dataKey: 'list',
        title: this.ColumnUtil.instResultColumns,
        localSearch: true, // 本地搜索
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    // 指令证券表格相关
    instStockMsg = {
        returnData: { list: [] },
        dataKey: 'list',
        title: [],
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    tableLoading: boolean = false; // 结果表数据加载
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    stockType: any[] = []; // 证券类别下拉
    instructionStatus = {
        '0': '已归档',
        '1': '已下达成功',
        '3': '已撤销',
        // '2': '已归档',
    };
    orderUsers: any[] = []; // 下单人下拉列表

    tabsLoading: boolean = false;

    stockLoading: boolean = false;
    clickRecord: any = {}; // 当前主表格点击的条目
    rowClickSetTime = null;
    instructionDetail: any = {};
    instStockDataSource: any[] = []; // 指令证券表数据
    instResultDataSource: any[] = []; // 指令结果表数据
    type: string = '';

    sortProp: string = 'directTime'; // 排序字段
    sortOrder: string = 'descending'; // 排序方式
    commonField = this.ColumnUtil.commonFieldSort;

    extraField: any = {};
    marketCodes: any = {};
    isShowTooltip: boolean = false;

    allStockType: any[] = []; // 所有证券类别数据
    stockTypePojo: any = {};
    allOrderDirection: any[] = []; // 所有订单方向数据
    noData: boolean = true; // 是否有指令数据
    instructionInfoUrl: string = '/instruction/cwOpenFundInstruction';

    @Watch('renderCount')
    onWatchRenderCount() {
        this.getInstruction(this.searchForm, this.pages);
    }

    hideVisible: boolean = true; // 是否隐藏
    assetCodeSelectData: any[] = [];
    fundAccountCodeSelectData: any[] = [];
    async mounted() {
        if (this.SHOW_SECURITY) {
            this.$axios.get('/asset/list/byFundCode').then((res: any) => {
                this.assetCodeSelectData = res;
            });
            this.$axios.get('/fdAc/list/byFundCode').then((res: any) => {
                this.fundAccountCodeSelectData = res;
            });
        }
        this.detailFields = this.ColumnUtil.handleDetailFieldsOnSecurity(this.detailFields, true, this.ColumnUtil.otherAssetColumns, 'id');

        this.tableColumns = this.ColumnUtil.handleTableColumns(this.tableColumns, 'id');

        // 价格模式
        let priceTypeTemp = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        this.investPriceSelectData = DictionConstUtil.ListToPojo(priceTypeTemp);
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
        // 证券类别
        // this.stockType = await DictionConstUtil.FNStockType();
        // 下单人下拉列表
        this.$axios.post('instruction/user/select').then((res: any) => {
            this.orderUsers = res;
        });
        // 获取所有证券类别 (用于筛选订单方向)
        this.allStockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        this.stockTypePojo = DictionConstUtil.ListToPojo(this.allStockType);
        this.getStockType();
        // 获取委托方向下拉
        this.getOrderDirectionData();
        // 获取所有订单方向
        this.allOrderDirection = await SGU_CACHE('TradeDirection', '/dict/tradeDirections', []);
        // this.getInstruction(this.searchForm, this.pages);
        this.queryLayout();
        this.marketCodes = DictionConstUtil.ListToPojo(await DictionConstUtil.FNMarketType());
        let columns = this.ColumnUtil.instStockColumns;
        columns[11] = {
            name: '指令价格',
            val: 'instPrice',
            width: 100,
            type: 'func',
            funcBody: value => (value != undefined ? numberFormat(value, 4) : '--'),
        };
        columns.splice(
            8,
            0,
            { name: '转入组合编码', val: 'destCombiId', minWidth: 150 },
            { name: '转入组合名称', val: 'destCombiName', minWidth: 150 },
            { name: '转入证券代码', val: 'destSecurityCode', minWidth: 120 },
            { name: '转入证券名称', val: 'destSecurityName', minWidth: 120 },
            {
                name: '转入投资类型',
                val: 'investType',
                minWidth: 120,
                type: 'func',
                funcBody: (value, row) => (row['originalDirection'] === 'E' && value ? this.Invest.investType[value] : '--'),
            },
            { name: '巨额赎回', val: 'bulkType', minWidth: 120, type: 'func', funcBody: value => (value ? this.Invest.bulkType[value] : '--') }
        );
        this.instStockMsg.title = columns;
    }

    beforeUpdate() {
        this.$nextTick(() => {
            // 在数据加载完，重新渲染表格
            (this.$refs['table'] as any).doLayout();
        });
    }

    query() {
        this.searchForm.directDate = Number(this.directDate) || null;
        this.clickRecord = {};
        this.currentClickRow = this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
    }

    getEntryslist(val: any) {
        this.searchForm.fundCode = val;
    }

    // 排序改变
    changeTableSort(column: any): void {
        this.sortProp = column.prop;
        this.sortOrder = column.order;
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        if (sortType) {
            this.searchForm.sort = this.findName(column.prop, sortType);
        } else {
            this.searchForm.sort = 'D_DIRECT_DATE ' + 'DESC' + ',' + 'D_DIRECT_TIME ' + 'DESC';
        }

        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
    }

    // 获取排序字段名称
    findName(name: string, order: string): string {
        let value = '';
        let field = '';
        let allFields = { ...this.commonField, ...this.ColumnUtil.fundTransferFieldSort };

        if (name === 'directTime') {
            value = 'D_DIRECT_DATE' + ' ' + order + ',' + 'D_DIRECT_TIME' + ' ' + order;
        } else if (name === 'intoInvestType') {
            value = 'C_INVEST_TYPE_NAME' + ' ' + order;
        } else {
            for (const key in allFields) {
                if (name === key) {
                    field = allFields[key];
                }
            }
            value = field + ' ' + order;
        }
        return value;
    }

    // getInstruction(param: any, pages: any) {
    //     this.tableLoading = true;
    //     this.$axios
    //         .post('instruction/cwOpenFundInstruction', {
    //             ...this.searchForm,
    //             paging: {
    //                 currentPage: pages.currentPage,
    //                 pageSize: pages.pageSize,
    //             },
    //         })
    //         .then((res: any) => {
    //             this.dataSource = res.list;
    //             this.pages.total = res.total;
    //             if (this.dataSource.length) {
    //                 this.clickRecord = this.dataSource[0] || {};
    //                 this.currentClickRow = this.clickRecord;
    //                 if (this.clickRecord.instStatus == '0') {
    //                     this.type = 'history';
    //                 } else {
    //                     this.type = '';
    //                 }
    //                 // if (moment(this.clickRecord.directDate).isBefore(moment().format('YYYYMMDD'))) {
    //                 //     this.type = 'history';
    //                 // } else {
    //                 //     this.type = '';
    //                 // }
    //                 (this.$refs['table'] as any).setCurrentRow(this.dataSource[0]);
    //                 this.handleRow(this.clickRecord);
    //                 this.noData = false;
    //             } else {
    //                 this.$set(this.instStockMsg.returnData, 'list', []);
    //                 this.$set(this.instResultMsg.returnData, 'list', []);
    //                 this.noData = true;
    //             }
    //             this.tableLoading = false;
    //         })
    //         .catch(() => {
    //             this.tableLoading = false;
    //         });
    // }

    getStockType() {
        this.$axios.get('/dict/instruction/stockType/' + 7).then((res: any) => {
            this.stockType = res;
        });
    }
    // 获取证券代码下拉框数据
    getstockCodeList(value: string) {
        this.selectLoading = true;
        this.$axios
            .post('/dict/stock/report/select/' + 5, {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            });
    }

    handleStockVisibleChange(val) {
        if (!val) {
            this.getstockCodeList('');
        }
    }

    // 获取委托方向
    getOrderDirectionData() {
        this.$axios.get('/dict/instruction/direction/' + 7).then((res: any) => {
            this.orderDirectionData = res;
        });
    }

    // 格式化日期
    formatterDate(row: any) {
        let date = dateFormat(row.directDate);
        let time = timeFormat(row.directTime);
        let dateTime = date + ' ' + time;
        return dateTime.trim() ? dateTime : '--';
    }

    // 修改指令
    handleUpdateInst(row: any) {
        this.$emit('changeTab', row);
    }

    // 查看按钮点击
    handleBtnLook(obj: any): void {
        this.$emit('handelOperate', { record: obj.row, history: this.type === 'history', clickRecord: this.clickRecord });
    }

    // // 撤单事件
    // handleBtnDel(row: any): void {
    //     this.cancelOrder.instNo = row.instNo;
    //     this.cancelOrder.originOuterOrderCode = row.outerOrderCode;
    //     this.$confirm('确认是否撤单?', '提示', {
    //         confirmButtonText: '确定',
    //         cancelButtonText: '取消',
    //         type: 'warning',
    //     })
    //         .then(() => {
    //             this.$axios
    //                 .post('/dataEngine/order/cancelOrder', this.cancelOrder)
    //                 .then((res: any) => {
    //                     this.yh_message_success('撤单成功');
    //                     this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
    //                 })
    //                 .catch(() => {
    //                     this.yh_message_error('撤单失败');
    //                 });
    //         })
    //         .catch(() => {
    //             this.yh_message_info('已取消撤单');
    //         });
    // }

    // 设置是否禁用
    handleDisabled(row: any): boolean {
        let userCode = getUser().userCode;
        return !(row['instStatus'] == '1' && (userCode == row.directUser || getUser().superuser));
    }

    // 按钮点击
    handleButtonClick(action: string): void {
        if (action === 'layout') {
            this.layoutDialog = true;
        } else if (action === 'hide') {
            this.hideVisible = !this.hideVisible;
            console.log(this.hideVisible, 'hideVisible');
        }
    }

    // 点击单行
    handleRow(obj: any): void {
        this.clickRecord = obj;
        this.clickRecord.stockTypeName = this.stockTypePojo[this.clickRecord.stockType];
        this.currentClickRow = obj;

        if (obj.instStatus == '0') {
            this.type = 'history';
        } else {
            this.type = '';
        }
        this.getInstructionInfo();
    }

    // // 查询指令证券和指令结果
    // getInstructionInfo() {
    //     this.tabsLoading = true;
    //     this.stockLoading = true;

    //     let url = '';
    //     if (this.type === 'history') {
    //         url =
    //             '/instruction/inst/history/all/' +
    //             this.currentClickRow.instNo +
    //             '/' +
    //             this.currentClickRow.outerOrderCode +
    //             '?serialNo=' +
    //             this.currentClickRow.serialNo;
    //     } else {
    //         url =
    //             '/instruction/inst/all/' +
    //             this.currentClickRow.instNo +
    //             '/' +
    //             this.currentClickRow.outerOrderCode +
    //             '?serialNo=' +
    //             this.currentClickRow.serialNo;
    //     }
    //     this.$axios.get(url).then((res: any) => {
    //         let instStockDataSource = [];
    //         let instResultDataSource = [];
    //         if (res.deposits && res.deposits.length > 0) {
    //             instStockDataSource = instStockDataSource.concat(res.deposits);
    //         }
    //         if (res.repos && res.repos.length > 0) {
    //             instStockDataSource = instStockDataSource.concat(res.repos);
    //         }
    //         if (res.stocks && res.stocks.length > 0) {
    //             instStockDataSource = instStockDataSource.concat(res.stocks);
    //         }
    //         instStockDataSource.forEach((item, i) => (item.key = item.serialNo + '-' + i));
    //         if (res.pleds && res.pleds.length > 0) {
    //             res.pleds.forEach((item, i) => (item.key = item.serialNo + '-' + i));
    //         }
    //         if (res.results && res.results.length > 0) {
    //             res.results.forEach((item, i) => (item.key = item.entryCode + '-' + i));
    //             res.results = res.results.sort(sortBy('thresholdType', 'desc'));
    //         }
    //         this.tabsLoading = false;
    //         this.stockLoading = false;
    //         this.$set(this.instStockMsg.returnData, 'list', instStockDataSource);
    //         this.instStockMsg.returnData.list.forEach((ele) => {
    //             ele.marketCode = this.marketCodes[ele.marketCode];
    //         });
    //         instResultDataSource = res.results;
    //         // instResultDataSource = res.results.filter((itme: any) => itme.thresholdType !== '4');
    //         this.$set(this.instResultMsg.returnData, 'list', instResultDataSource);
    //     });
    // }

    // 分页
    handleCurrentChange(curPage: number): void {
        this.pages.currentPage = curPage;
        this.getInstruction(this.searchForm, this.pages);
    }

    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        // this.tableLoading = true;
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/CW_INST_INFO')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            // 新增固定列 考虑到该列已被存入数据库问题
            this.selectedFieldList = this.selectedFieldList.filter(item => {
                let distinctIds = this.fixedFieldList.filter(fixedFieldListItem => {
                    return fixedFieldListItem.id === item.id;
                });
                if (distinctIds.length > 0) {
                    return false;
                } else {
                    return true;
                }
            });
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            this.tableKey++;
        } else {
            this.showFieldList = this.tableColumns;
            this.selectedFieldList = this.tableColumns;
            this.tableKey++;
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/inst-info';

#instructionInfo-content {
    padding: 10px;
    height: 100%;

    .table-content {
        border: 1px solid #d7d7d7;
        border-top: none;
        margin-top: 10px;
        height: calc(60% - 125px);

        /deep/.el-table {
            th {
                padding: 5px 0 !important;
                background-color: #e8f3ff !important;
                .cell {
                    //   min-width: 30px;
                    white-space: nowrap; /* 文本在一行显示，不换行 */
                    text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本。*/
                    overflow: hidden; /* 超出部分隐藏 */
                }
            }
        }
    }
    .tab-content {
        border: 1px solid #d7d7d7;
        margin-top: 10px;
        height: 40%;
        .detail-container {
            height: 100%;
            padding: 4px 10px;
            width: 100%;
            overflow-x: auto;

            .detail-item {
                width: 180px;

                > span {
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
            }
        }

        .detail-row {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            grid-gap: 10px;
            padding: 5px 0;
            width: 135%;
            > span {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
            .text {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
        .el-tab-pane {
            color: black;
        }
    }
}
</style>
